//
//  MYUserAccountModel.swift
//  MYWeiBo
//
//  Created by apple on 16/5/14.
//  Copyright © 2016年 YanMo. All rights reserved.
//

import UIKit

class MYUserAccountModel: NSObject {
    static let sharedInstance:MYUserAccountModel = MYUserAccountModel()
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //全局的账号
    var userAccount : MYUserAccount?
    
    //提供一个属性，让外界调用，是不是已经在登录过了
    var isUserLogin: Bool {
        get {
            return userAccount != nil //不为空，则登录过
        }
    }
    
    override init() {
        super.init()
        //全局加载一次
        userAccount = loadUserAccount()
    
    }
    
    ///加载用户的信息
    func loadUserInfo(loadUserInfoCallBack:() -> ()){
        //guard不为空的时候，才能往下执行
        guard let access_token = userAccount?.access_token else{
            MYPrint(items: "access_token为空")
            return
        }
        guard let uid = userAccount?.uid else{
        
            MYPrint(items: "uid为空")
            return
        }
        //到这一步，授权通过
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        //发送网络请求
        MYAFNetworkingTool.shardInstance.request(requestmeMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responseOject) -> Void in
//                MYPrint(items: "取得用户信息responseOject:\(responseOject)")
                //取得数据
            if let result = responseOject as? [String:AnyObject]{
            
                //通过key来取用户名与头像的url
                let screen_name = result["screen_name"] as? String
                let avatar_large = result["avatar_large"] as? String
                //赋值给当前模型
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                //保存用户信息信息地沙盒中
                self.saveUserAccount()
                //把信息回调出去
                loadUserInfoCallBack()
                
            }
            
            }) { (_, error) -> Void in
                MYPrint(items: "加载用户信息出错了\(error)")
                
        }
        
    
    
    }
    //保存信息到沙盒中去
    private func saveUserAccount(){
        if let account = userAccount{
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        }
    }
    
    /**
     * 归档账号
     */
    func loadAccountToken(code: String,errorCallBack:(error:NSError?) -> ()){
        let urlString = "oauth2/access_token"
        //参数,数组的形式的
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "gran_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        //发送post
        MYAFNetworkingTool.shardInstance.request(requestmeMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
//            MYPrint(items: "取得access_token成功，access_token = \(responseObject)")
            
            //使用字典转模型
            if let result = responseObject as? [String:AnyObject]
            {
                //字典转模型
                let  userAccount = MYUserAccount(dict:result)
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
                //保存模型
                self.userAccount = userAccount
                self.saveUserAccount()
                errorCallBack(error: nil)
            }else{
                MYPrint(items: "返回数据字典转模型失败")
            }
            
            }, failure: { (task, error) -> Void in
                errorCallBack(error : error)
        })
     
    }
    /**
    * 解档账号
    */
    func loadUserAccount() -> MYUserAccount? {
        
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as?MYUserAccount {
            //判断是否过期
            if userAccount.expirsDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending{
                //没有过期
                return userAccount
            }else{
            
                return nil
            }
        }else{
        
             return nil
        }
  
    }
    
    
}













